#include <QSslKey>
#include <QSslConfiguration>
#include <QFile>
#include "SslServer.h"

SslServer::SslServer(QObject *parent)
    : QTcpServer(parent)
{

}

SslServer::~SslServer()
{

}

QByteArray readAll(const char *path)
{
    QFile f(path);
    f.open(QIODevice::ReadOnly);
    return f.readAll();
}
void SslServer::incomingConnection(qintptr socketDescriptor)
{
    QSslSocket *s = new QSslSocket(this);
    if (s->setSocketDescriptor(socketDescriptor)) {

        QSslConfiguration sslConfiguration;
        QFile keyFile(QStringLiteral("server.key"));
        keyFile.open(QIODevice::ReadOnly);
        QSslKey sslKey(&keyFile, QSsl::Rsa, QSsl::Pem);
        keyFile.close();

        QList<QSslCertificate> certificates;
        if (s->peerAddress().isLoopback())
        {
            certificates.append(QSslCertificate::fromPath("server_localhost.crt"));
        }
        certificates.append(QSslCertificate::fromPath("server_119_29_159_124.crt"));
        certificates.append(QSslCertificate::fromPath("server_weizehua_vicp_cc.crt"));

        sslConfiguration.setCaCertificates(QSslCertificate::fromPath("ca.crt"));
        sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyPeer);
        sslConfiguration.setLocalCertificateChain(certificates);
        sslConfiguration.setPrivateKey(sslKey);
        //sslConfiguration.setProtocol(QSsl::TlsV1_2);

        s->setSslConfiguration(sslConfiguration);

        s->startServerEncryption();
        addPendingConnection(s);
    }
    else {
        delete s;
    }
}

QSslSocket *SslServer::nextPendingConnection()
{
    return static_cast<QSslSocket *>(QTcpServer::nextPendingConnection());
}
